//
//  UserInfomationVC.swift
//  LeTu
//
//  Created by gy on 2023/12/11.
//

import UIKit

class UserInfomationVC: BaseViewController {
    
    private var viewModel = UserInfomationVM()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configUI()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        getData()
    }
    private func getData() {
        kUserManager.getUserInfomation { [weak self] dialog in
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.viewModel.updateItems()
                strongSelf.infoTableView.reloadData()
            }
        }
    }
    
    // MARK: - configUI
    func configUI() {
        
        navIsHidden = false
        title = "账户信息".localized
        
        view.addSubview(infoTableView)
        infoTableView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        infoTableView.delegate = self
        infoTableView.dataSource = self
        infoTableView.register(cellClass: BaseArrowTableViewCell.self)
        infoTableView.register(cellClass: UserInfomationAvatarTableViewCell.self)
        
    }
    private lazy var infoTableView: UITableView = {
        let infoTableView = UITableView()
        infoTableView.tableFooterView = UIView()
        infoTableView.showsVerticalScrollIndicator = false
        return infoTableView
    }()

}

extension UserInfomationVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 68
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel.items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = viewModel.items[indexPath.row]
        if item.title == "头像" {
            let cell = tableView.dequeueReusableCell(UserInfomationAvatarTableViewCell.self, indexPath: indexPath)
            cell.setItem(item)
            return cell
        }
        let cell = tableView.dequeueReusableCell(BaseArrowTableViewCell.self, indexPath: indexPath)
        cell.setItem(item)
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let item = viewModel.items[indexPath.row]
        if item.title == "头像".localized {
            AppActionSheet(titles: [AppActionSheetItem(title: "从相册选择".localized), AppActionSheetItem(title: "用相机拍照".localized)]) { [weak self] title, index in
                   guard let strongSelf = self else { return }
                   
                   if title == "从相册选择".localized {
                       // 相册
                       strongSelf.selectImage()
                   } else if title == "用相机拍照".localized {
                       // 拍照
                       strongSelf.takePhotos()
                   }

            }.show()
        } else if item.title == "昵称".localized {
            show(ChangeNicknameVC(viewType: .nickname), sender: nil)
        }
        
    }
    
}

extension UserInfomationVC : UIImagePickerControllerDelegate , UINavigationControllerDelegate {
    
    // 选择照片
    func selectImage() {
        
        AlbumPermissionsManager.authorizePhotoWith { [weak self] status in
            
            guard let strongSelf = self else { return }
            
            if (!status) {
                AlbumPermissionsManager.unAuthorizeAlert(vc: strongSelf, title: "相册权限未开启".localized , message: "请在“设置-\(Device.getAppName().localized)”中，允许应用访问你的相册。".localized)
            } else {
                let imagePicker = UIImagePickerController()
                imagePicker.allowsEditing = false
                imagePicker.sourceType = .photoLibrary
                imagePicker.delegate = strongSelf
                imagePicker.modalPresentationStyle = .fullScreen
                strongSelf.present(imagePicker, animated: true)
            }
        
        }

        
    }
    // 拍照
    func takePhotos() {

        AlbumPermissionsManager.authorizeCameraWith { (status) in
            
            if (!status) {
                AlbumPermissionsManager.unAuthorizeAlert(vc: self, title: "相机权限未开启".localized , message: "请在“设置-\(Device.getAppName().localized)”中，允许应用访问你的相机。".localized)
            } else {
                // 拍照
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = false
                cameraPicker.sourceType = .camera
                //在需要的地方present出来
                self.present(cameraPicker, animated: true, completion: nil)
            }
            
        }
        
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        
        guard let imageData = selectedImage.compressImage(image: selectedImage, maxLength: 1024*1024) else { return }
        
        viewModel.picData = imageData
        showIndicator()
        viewModel.updateAvatar { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            DispatchQueue.main.async {
                strongSelf.showMessage(message: dialog.message)
                strongSelf.hideIndicator()
                if dialog.code == 200 {
                    strongSelf.viewModel.updateItems()
                    strongSelf.infoTableView.reloadSections([0], with: .none)
                }
            }
            
        }
        
        picker.dismiss(animated: true, completion: nil)
        
    }
    
}






